from flask import Flask, render_template, request, redirect, url_for, flash
from werkzeug.utils import secure_filename
import os
import random
import string
import json

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024  # 2MB

os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# 生成8位随机文件名
def random_filename(ext=None):
    if ext is None:
        ext = '.txt'
    return ''.join(random.choices(string.ascii_letters + string.digits, k=8)) + ext

# 只允许.txt和.pdf文件
def allowed_file(filename):
    return filename.lower().endswith('.txt') or filename.lower().endswith('.pdf')

INFO_JSON = os.path.join(app.config['UPLOAD_FOLDER'], 'fileinfo.json')

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files.get('file')
        remark = request.form.get('remark', '').strip()
        if not file or file.filename == '':
            flash('请选择要上传的TXT或PDF文件', 'error')
            return redirect(url_for('index'))
        if not allowed_file(file.filename):
            flash('只允许上传.txt和.pdf文件', 'error')
            return redirect(url_for('index'))
        orig_filename = secure_filename(file.filename)
        ext = os.path.splitext(orig_filename)[1].lower()
        new_filename = random_filename(ext)
        try:
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))
            # 保存信息到 JSON
            info = {'new': new_filename, 'orig': orig_filename, 'remark': remark}
            if os.path.exists(INFO_JSON):
                with open(INFO_JSON, 'r', encoding='utf-8') as f:
                    infos = json.load(f)
            else:
                infos = []
            infos.append(info)
            with open(INFO_JSON, 'w', encoding='utf-8') as f:
                json.dump(infos, f, ensure_ascii=False, indent=2)
            flash(f'文件 {orig_filename} 上传成功！新文件名：{new_filename}', 'success')
        except Exception as e:
            flash(f'文件保存失败: {e}', 'error')
        return redirect(url_for('index'))

    # 展示文件列表
    file_infos = []
    if os.path.exists(INFO_JSON):
        with open(INFO_JSON, 'r', encoding='utf-8') as f:
            try:
                file_infos = json.load(f)
            except Exception:
                file_infos = []
    return render_template('index.html', files=file_infos)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)